package com.dm.cloud.inteceptor;

import com.dm.cloud.common.CloudConstant;
import com.dm.cloud.common.R;
import com.dm.cloud.properties.CloudSecurityProperties;
import com.dm.cloud.utils.WebUtils;
import lombok.NonNull;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServerProtectInterceptor implements HandlerInterceptor {

    private CloudSecurityProperties properties;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler){

        if (!properties.getOnlyFetchByGateway()) {
            return true;
        }

        String token = request.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);

        String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));

        if (gatewayToken.equals(token)) {
            return true;
        } else {
            R<String> resultData = new R<>();
            resultData.setType("failure");
            resultData.setCode(901);//需要通过网关访问
            resultData.setMessage("请通过网关访问资源");

            WebUtils.writeJson(response, resultData);

            return false;
        }
    }

    public void setProperties(CloudSecurityProperties properties) {
        this.properties = properties;
    }
}